package com.googlelogin;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Event.Creator;
import com.google.api.services.calendar.model.EventAttendee;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.gson.Gson;
import com.propertypoint.presentation.model.GoogleUser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.TimeZone;

public class GoogleAuthHelper {

	private static final String CLIENT_ID = "658870867053-tonmlumqaf6952tsecp2s1ld2jsdqan6.apps.googleusercontent.com";
	private static final String CLIENT_SECRET = "zWtrN490KyobIW7FRrEVUoeN";
	private static final String SCOPE = "https://www.googleapis.com/auth/calendar";
	private static final String redirectUrl = "http://localhost:8080/PropertyPoint/GoogleCallbackServlet";
	private static final Iterable<String> SCOPE2 = Arrays.asList("https://www.googleapis.com/auth/userinfo.profile;https://www.googleapis.com/auth/userinfo.email".split(";"));
	
	private static final String USER_INFO_URL = "https://www.googleapis.com/oauth2/v1/userinfo";
	private static final JsonFactory JSON_FACTORY = new JacksonFactory();
	private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
	JacksonFactory jsonFactory = new JacksonFactory();
	private String stateToken;
	public static GoogleAuthorizationCodeFlow flow;
	static Credential credentials = null;

	public String setUp() throws IOException {

		HttpTransport httpTransport = new NetHttpTransport();
		
		ArrayList<String> scopes = new ArrayList<String>();
		scopes.add(SCOPE);
		scopes.add("https://www.googleapis.com/auth/userinfo.profile");
		scopes.add("https://www.googleapis.com/auth/userinfo.email");

		if(null == flow){
		flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
				jsonFactory, CLIENT_ID, CLIENT_SECRET,
				scopes).setAccessType("online")
				.setApprovalPrompt("auto").build();
		}
		
		String url = flow.newAuthorizationUrl().setRedirectUri(redirectUrl)
				.build();

		generateStateToken();
		String loginUrl = buildLoginUrl();
		return loginUrl;
	}

	private void generateStateToken() {

		SecureRandom sr1 = new SecureRandom();

		stateToken = "google;" + sr1.nextInt();

	}

	public String buildLoginUrl() {

		final GoogleAuthorizationCodeRequestUrl url = flow
				.newAuthorizationUrl();

		return url.setRedirectUri(redirectUrl).setState(stateToken).build();
	}

	public String getStateToken() {
		return stateToken;
	}
	
	  static Credential exchangeCode(String authorizationCode) {
		    try {
		      GoogleAuthorizationCodeFlow flow = getFlow();
		      if(null == credentials){
		      GoogleTokenResponse response =
		          flow.newTokenRequest(authorizationCode).setRedirectUri(redirectUrl).execute();
		      credentials = flow.createAndStoreCredential(response, null);
		      }
		    } catch (IOException e) {
		      System.err.println("An error occurred: " + e);
		      
		    }
		    return credentials;
		  }
	  
	public GoogleUser getUserInfoJson( ) throws IOException {
		setUp() ;
//		final GoogleTokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(redirectUrl).execute();
//		final Credential credential = flow.createAndStoreCredential(response, null);
		final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credentials);

		// Make an authenticated request
		final GenericUrl url = new GenericUrl(USER_INFO_URL);
		final HttpRequest request = requestFactory.buildGetRequest(url);
		request.getHeaders().setContentType("application/json");
		final String jsonIdentity = request.execute().parseAsString();
		Gson gson = new Gson();
		GoogleUser googleUser = gson.fromJson(jsonIdentity, GoogleUser.class);
		return googleUser;

	}
	
	public void createEvent(final String authCodes) throws IOException{
		
		setUp() ;
//		final GoogleTokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(redirectUrl).execute();
//		final Credential credential = flow.createAndStoreCredential(response, null);
		final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credentials);
	
		Event event = new Event();

		event.setSummary("PropertyPoint Appointment Test");
		event.setLocation("NTU Canteen New ");

		ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>();
		attendees.add(new EventAttendee().setEmail("azharnuz@gmail.com"));
		attendees.add(new EventAttendee().setEmail("tharindu.ssl@gmail.com"));
		//attendees.add(new EventAttendee().setEmail("snipergacp@gmail.com"));
		//attendees.add(new EventAttendee().setEmail("spkeerthiga@gmail.com"));
		//attendees.add(new EventAttendee().setEmail("ramboisme2011@gmail.com"));
		
		// ...
		event.setAttendees(attendees);

		Date startDate = new Date();
		startDate = new Date(startDate.getTime()+360000000);
		Date endDate = new Date(startDate.getTime() + 36000000);
		DateTime start = new DateTime(startDate, TimeZone.getTimeZone("UTC"));
		event.setStart(new EventDateTime().setDateTime(start));
		DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
		event.setEnd(new EventDateTime().setDateTime(end));
		Calendar service = new Calendar(HTTP_TRANSPORT, jsonFactory, credentials);
		Creator cre = new Creator();
		cre.setDisplayName("Nuzly Azhar");
		cre.setEmail("nuzly86@gmail.com");
		event.setCreator(cre);
		//Calendar service = null;
		Event createdEvent = null;;
		try {
			createdEvent = service.events().insert("primary", event).execute();
		} catch (IOException e) {
			
			e.printStackTrace();
		}

		//System.out.println(createdEvent.getId());
	}

	
public void createEvent(String summary, String description, String customerEmail, String location, Date apointmentDate, GoogleUser googleUser) throws IOException{
		
		setUp() ;
//		final GoogleTokenResponse response = flow.newTokenRequest(authCode).setRedirectUri(redirectUrl).execute();
//		final Credential credential = flow.createAndStoreCredential(response, null);
		final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credentials);
	
		Event event = new Event();

		event.setSummary(summary);
		event.setLocation(location);
		event.setDescription(description);

		ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>();
		attendees.add(new EventAttendee().setEmail(customerEmail));
		//attendees.add(new EventAttendee().setEmail("snipergacp@gmail.com"));
		//attendees.add(new EventAttendee().setEmail("spkeerthiga@gmail.com"));
		//attendees.add(new EventAttendee().setEmail("ramboisme2011@gmail.com"));
		
		// ...
		
	
		event.setAttendees(attendees);

		Date startDate = new Date();
		startDate = new Date(startDate.getTime()+360000000);
		Date endDate = new Date(apointmentDate.getTime() + 3600000);
		DateTime start = new DateTime(apointmentDate, TimeZone.getTimeZone("UTC"));
		event.setStart(new EventDateTime().setDateTime(start));
		DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
		event.setEnd(new EventDateTime().setDateTime(end));
		Calendar service = new Calendar(HTTP_TRANSPORT, jsonFactory, credentials);
		Creator cre = new Creator();
		cre.setDisplayName(googleUser.getGiven_name());
		cre.setEmail(googleUser.getEmail());
		event.setCreator(cre);
		//Calendar service = null;
		Event createdEvent = null;;
		try {
			createdEvent = service.events().insert("primary", event).execute();
		} catch (IOException e) {
			
			e.printStackTrace();
		}

		//System.out.println(createdEvent.getId());
	}
	public static GoogleAuthorizationCodeFlow getFlow() {
		return flow;
	}

	public static void setFlow(GoogleAuthorizationCodeFlow flow) {
		GoogleAuthHelper.flow = flow;
	}
	
	  static Calendar buildService(GoogleCredential credentials) {
		    HttpTransport httpTransport = new NetHttpTransport();
		    JacksonFactory jsonFactory = new JacksonFactory();

		    return new Calendar.Builder(httpTransport, jsonFactory, credentials)
		        .build();
		  }
	  
	  static void storeCredentials(String userId, Credential credentials) {
		   
		  }
	

}
